var express = require('express');
var router = express.Router();

/** 模块引入 
 * bi：bi子项目
*/
var commonModule = require('./bi/common');//公共接口
var analyseManageModule = require('./bi/analyseManage');//分析管理
var dataArrangeModule = require('./bi/dataArrange')  //数据整理
var modules = {
  common: new commonModule(),
  analyseManage: new analyseManageModule(),
  dataArrange: new dataArrangeModule()
}

//数字字符串转换
function string2Number(v) {
  return /^\d+$/.test(v) ? parseInt(v) : v;
}

//接口请求
async function goAction(params, req, res, next) {
  let _params = params;
  let _moduleKey = _params.module, _actionKey = _params.action;
  //检测模块是否存在
  if (modules.hasOwnProperty(_moduleKey)) {
    let _module = modules[_moduleKey];
    //检测模块中的接口是否定义
    if (typeof _module[_actionKey] === "function") {
      //数据端接口参数
      let $params = {};

      // $params.data = req.method === "GET" ? JSON.parse(req.query) : req.body;

      //  所有接口都是post
      $params.data = req.body;
      try {
        let _user = req.headers.user || {};
        $params.user = _user;
       
        $params.operator = _user.userId;

        $params.lang = $params.lang || req.headers.lang || "cn";
        // $params.userId = string2Number($params.userId || _user.userId);
        $params.tenantId = $params.tenantId || _user.tenantId; //租户
       // $params.organizationId = string2Number($params.organizationId || _user.organizationId); //公司
        //$params.deptId = string2Number($params.deptId || _user.deptId); //部门/
        //忽略默认参数[tenantId,organizationId,deptId]
        params.ignore && params.ignore.map(_key => {
          delete params[_key];
        });
        $params.ip = '';
        // $params.operator=1;
        // $params.tenantId=1;
        $params.sid = 1;
        $params.source = "PC";
        $params.version = "1.0";

        //响应结果由业务模块控制
        _module[_actionKey]($params, res, req);
      } catch (error) {
        console.log("模块[" + _moduleKey + "]接口[" + _actionKey + "]错误====>", error);
        res.json({ status: -1, data: { message: "The interface action error: " + error } });
      }
    }
    else {
      res.json({ status: -1, data: { message: "The interface action is invalid" } });
    }
  }
  else {
    res.json({ status: -1, data: { message: "The interface module is invalid" } });
  }
}

/** get */
// router.get("/", function (req, res, next) {
//   // console.log(req.query, "req.query===>get");
//   goAction(req.query, req, res, next);
// });
//
// /** post */
// router.post("/", function (req, res, next) {
//   // console.log(req.body, "req.body===>post");
//   goAction(req.body, req, res, next);
// });

router.post('*', function ( req, res, next ) {
  const parseUrl = req.url.split('/');
  if(parseUrl.length !== 3)  return res.json({status: -1, data: { message: "The interface module is invalid" } });
  let params = {
    module: parseUrl[1],
    action: parseUrl[2]
  };
  goAction(params, req, res, next);
})

module.exports = router;
